package com.longnuoqi.mydoctor.activity;


import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.yunhe.mydoctor.R;


import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2016/1/6.
 */
public class NearbyStoreActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences;
    private boolean isLogin = false;
    private String access_token;
    private static final String TYPE = "store";

    private ImageView back;
    private ImageView share;
    private ImageView favorite;
    private int id;
    private String name;
    private String address;
    private double x;
    private double y;

    private MapView mapView;
    private AMap aMap;

    private GeocodeSearch geocodeSearch;
    private Marker geoMarker;
    private Marker regeoMarker;
    private LatLonPoint latLonPoint;//经纬度点

    private String addressName;

    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(NearbyStoreActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearby_store_layout);
        ActivityCollection.addActivity(this);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);

        savedInstanceState = getIntent().getExtras();
        id = savedInstanceState.getInt("id");
        name = savedInstanceState.getString("name");
        address = savedInstanceState.getString("address");
        x = savedInstanceState.getDouble("x");
        y = savedInstanceState.getDouble("y");
//        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
//        isLogin = sharedPreferences.getBoolean("islogin", false);
        Log.e("=====================", "store id:" + id);
        Log.e("=====================", "store name:" + name);
        Log.e("=====================", "store x:" + x);
        Log.e("=====================", "store y:" + y);
        initView();
        initMap();
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.store_back_btn);
        share = (ImageView) findViewById(R.id.store_share_btn);
        favorite = (ImageView) findViewById(R.id.store_favorite_btn);

        back.setOnClickListener(onClickListener);
        share.setOnClickListener(onClickListener);
        favorite.setOnClickListener(onClickListener);

        latLonPoint = new LatLonPoint(x, y);
        geocodeSearch = new GeocodeSearch(NearbyStoreActivity.this);
        geocodeSearch.setOnGeocodeSearchListener(geocodeSearchListener);
        getLatlon(name, 010);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.store_back_btn:
                    Intent intent = getIntent();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case R.id.store_share_btn:
                    Toast.makeText(NearbyStoreActivity.this, "分享", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.store_favorite_btn:
                    Toast.makeText(NearbyStoreActivity.this, "收藏", Toast.LENGTH_SHORT).show();
//                    if (isLogin) {
//                        if (TextUtils.isEmpty(name)) {
//                            Toast.makeText(NearbyStoreActivity.this, "数据正在加载中……", Toast.LENGTH_SHORT).show();
//                        } else {
//                            access_token = sharedPreferences.getString("access_token", "");
//                            VolleyUtil.initFavorite(NearbyStoreActivity.this, id, TYPE, access_token, name);
//                        }
//                    } else {
//                        Toast.makeText(NearbyStoreActivity.this, "请先登录！", Toast.LENGTH_SHORT).show();
//                    }
                    break;
                default:
                    break;
            }

        }
    };

    private void getLatlon(String name, int code) {
        GeocodeQuery query = new GeocodeQuery(name, String.valueOf(code));
        geocodeSearch.getFromLocationNameAsyn(query);
    }

    private void getAddress() {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 1000, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
    }

    private GeocodeSearch.OnGeocodeSearchListener geocodeSearchListener = new GeocodeSearch.OnGeocodeSearchListener() {
        @Override
        public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int errorCode) {
            if (errorCode == 0) {
                if (regeocodeResult != null && regeocodeResult.getRegeocodeAddress() != null && regeocodeResult.getRegeocodeAddress().getFormatAddress() != null) {
                    addressName = regeocodeResult.getRegeocodeAddress().getFormatAddress();
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()), 15));
                    regeoMarker.setPosition(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()));
                }
            }
        }

        @Override
        public void onGeocodeSearched(GeocodeResult geocodeResult, int errorCode) {
            if (errorCode == 0) {
                if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null && geocodeResult.getGeocodeAddressList().size() > 0) {
                    GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                    if (geocodeAddress.getLatLonPoint() == null) {
                        Toast.makeText(NearbyStoreActivity.this, "该地址不存在！或已搬迁！", Toast.LENGTH_SHORT).show();
                    } else {
                        LatLng latLng = new LatLng(geocodeAddress.getLatLonPoint().getLatitude(), geocodeAddress.getLatLonPoint().getLongitude());
                        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 15);
                        aMap.animateCamera(update);
                        geoMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                        geoMarker.setPosition(latLng);
                        geoMarker.setTitle(name);
                        geoMarker.setSnippet("详细地址：" + address);
                    }
                }
            } else {
                Toast.makeText(NearbyStoreActivity.this, "errorCode:" + errorCode, Toast.LENGTH_SHORT).show();
            }
        }
    };


    private void initMap() {
        if (mapView != null) {
            aMap = mapView.getMap();
            aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            //重写地图中心
            CameraPosition cp = aMap.getCameraPosition();
            CameraPosition cpnew = CameraPosition.fromLatLngZoom(new LatLng(31.22, 121.48), cp.zoom);
            CameraUpdate update = CameraUpdateFactory.newCameraPosition(cpnew);
            aMap.moveCamera(update);

            geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f));
            geoMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f));
            regeoMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

            MyLocationStyle myLocationStyle = new MyLocationStyle();
            //生成一个定位图标
            myLocationStyle.myLocationIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            myLocationStyle.strokeColor(android.R.color.black);
            myLocationStyle.strokeWidth(2);

            aMap.setMyLocationStyle(myLocationStyle);
            aMap.setMyLocationEnabled(true);//定义显示位图层，并且可以触发定位
            aMap.getUiSettings().setMyLocationButtonEnabled(true);//定义定位按钮允许显示
        }
    }

    //一定要重写Activity或Fragment对应的生命周期，因为地图属于第三方的提供，不会默认跟随android生命周期进行运作
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        ActivityCollection.removeActivity(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

}
